import config from "../../lib/config/config";
import wsEvents from "../wsEvents";
let startMonitor=false
export default class wsClient{
  run(){
    let self=this;
    let host=config.getConfigByKey('websocket').host
    let port=config.getConfigByKey('websocket').port
    let url=config.getConfigByKey('websocket').url
    let clientToken=config.getConfigByKey('clientToken')
    var ws = new WebSocket("ws://"+host+':'+port+'/'+url+"?clientToken="+clientToken);
    ws.onopen = function(){
      app.trigger(wsEvents.events.ON_LOG,"成功连接到集群")
    }
    ws.onmessage = function(e){
     let data=e.data;
     try {
       data=JSON.parse(data)
       app.trigger(data.event,data.msg)
     }
     catch (e){
       console.log(e)
     }
    }
    ws.onclose = function(e){
      app.trigger(wsEvents.events.ON_LOG,"集群断开连接:正在尝试重新连接")
      app.trigger(wsEvents.events.ON_WS_DISCONNECT)
      self.run()
    }
    ws.onerror = function(e){
      console.log(error);
    }
    if (startMonitor===false){
      startMonitor=true
    }
  }
}
